package netty.io.demo.Netty.echo.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class NettyClient {
  
  private static final Logger log = LoggerFactory.getLogger(NettyClient.class);
  private final int port;
  private final String host;
  
  NettyClient(int port, String host) {
    this.host = host;
    this.port = port;
  }
  
  void start() throws InterruptedException {
    // 线程组
    EventLoopGroup group = new NioEventLoopGroup(1);
    
    try {
      Bootstrap b = new Bootstrap();
      b.group(group)
          .channel(NioSocketChannel.class)
          .handler(new ClientHandler());
      
      // 同步阻塞 连接
      ChannelFuture cf = b.connect(host, port).sync();
      // 阻塞 直到channel 关闭
      cf.channel().closeFuture().sync();
    } finally {
      // 优雅关闭
      group.shutdownGracefully();
    }
  }
  
  public static void main(String[] args) throws InterruptedException {
    System.out.println("client start ...");
    new NettyClient(10020, "localhost").start();
    System.out.println("client end ...");
  }
}
